<template>
  <div>
    <template v-if="hasPermissions">
      <div class="base-container top-card">
        <div class="top-card-box">
          <img class="img" src="../assets/images/total_order.png" />
          <p class="num" id="totalUser">{{ formatNumberWithCommas(total.total_fee.toFixed(2)) }}</p>
          <p class="label">累计交易金额（元）</p>
        </div>
        <div class="top-card-box">
          <img class="img" src="../assets/images/total_amount.png" />
          <p class="num" id="totalOrder">{{ formatNumberWithCommas(total.total_order.toFixed(0)) }}</p>
          <p class="label">累计交易笔数</p>
        </div>
        <div class="top-card-box last-card">
          <img class="img" src="../assets/images/total_user.png" />
          <p class="num" id="totalCard">{{ formatNumberWithCommas(total.total_user.toFixed(0)) }}</p>
          <p class="label">总开卡数</p>
        </div>
      </div>

      <div class="base-container top-card mt-10px">
        <div class="top-card-box">
          <img class="img" src="../assets/images/total_order.png" />
          <p class="num" id="totalUser">{{ formatNumberWithCommas(today.total_fee.toFixed(2)) }}</p>
          <p class="label">今日交易金额（元）</p>
          <div class="compare-box">
            <img v-if="todayRes.total_fee_data.up_down == '+'" src="../assets/images/rise.png" class="icon" />
            <img v-if="todayRes.total_fee_data.up_down == '-'" src="../assets/images/fall.png" class="icon" />
            <p class="value">{{ todayRes.total_fee_data.ratio }}</p>
            <p class="value ml-10px">较昨日</p>
          </div>
        </div>
        <div class="top-card-box">
          <img class="img" src="../assets/images/total_amount.png" />
          <p class="num" id="totalOrder">{{ formatNumberWithCommas(today.total_order.toFixed(0)) }}</p>
          <p class="label">今日交易笔数</p>
          <div class="compare-box">
            <img v-if="todayRes.total_num_data.up_down == '+'" src="../assets/images/rise.png" class="icon" />
            <img v-if="todayRes.total_num_data.up_down == '-'" src="../assets/images/fall.png" class="icon" />
            <p class="value">{{ todayRes.total_num_data.ratio }}</p>
            <p class="value ml-10px">较昨日</p>
          </div>
        </div>
        <div class="top-card-box last-card">
          <img class="img" src="../assets/images/total_user.png" />
          <p class="num" id="totalCard">{{ formatNumberWithCommas(today.total_user.toFixed(0)) }}</p>
          <p class="label">今日开卡数</p>
          <div class="compare-box">
            <img v-if="todayRes.car_register_data.up_down == '+'" src="../assets/images/rise.png" class="icon" />
            <img v-if="todayRes.car_register_data.up_down == '-'" src="../assets/images/fall.png" class="icon" />
            <p class="value">{{ todayRes.car_register_data.ratio }}</p>
            <p class="value ml-10px">较昨日</p>
          </div>
        </div>
      </div>

      <div class="mt-10px flex">
        <div class="base-container flex-1">
          <div class="title-box">
            <p class="title">渠道订单趋势</p>
          </div>
          <div class="flex flex-between mt-10px">
            <div class="flex items-center">
              <el-select 
                multiple clearable collapse-tags
                v-model="lineOrderInfo.channelCode" 
                placeholder="请选择渠道（支持多选，最多选3个渠道）" 
                style="width: 320px"
                :multiple-limit="3"
                @clear="getOrderLineData"
                @remove-tag="getOrderLineData"
                @visible-change="handleOrderMultiSelect">
                <el-option
                  v-for="dict in channelList"
                  :key="dict.channelCode"
                  :label="dict.channelName"
                  :value="dict.channelCode"
                />
              </el-select>
              <el-radio-group v-model="lineOrderInfo.chartType" class="ml-10px" @change="getOrderLineData">
                <el-radio-button value="trade_pay_fee">交易金额</el-radio-button>
                <el-radio-button value="trade_count">交易笔数</el-radio-button>
                <el-radio-button value="trade_user">交易人数</el-radio-button>
              </el-radio-group>
            </div>
            <div class="flex items-center">
              <el-radio-group v-model="lineOrderInfo.lidu" class="mr-10px" @change="getOrderLineData">
                <el-radio-button value="day">日</el-radio-button>
                <el-radio-button value="week">周</el-radio-button>
                <el-radio-button value="month">月</el-radio-button>
              </el-radio-group>
              <el-date-picker 
                v-model="lineOrderInfo.searchDate"
                :clearable="false"
                type="daterange"
                value-format="YYYYMMDD"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 240px"
                :disabled-date="handleDisabledDate"
                @change="getOrderLineData">
              </el-date-picker>
            </div>
          </div>
          <div class="chart" id="orderChart"></div>
        </div>
      </div>

      <div class="mt-10px flex">
        <div class="base-container flex-1">
          <div class="title-box">
            <p class="title">渠道用户趋势</p>
          </div>
          <div class="flex flex-between mt-10px">
            <div class="flex items-center">
              <el-select 
                multiple clearable collapse-tags
                v-model="lineUserInfo.channelCode" 
                placeholder="请选择渠道（支持多选，最多选3个渠道）" 
                style="width: 320px"
                :multiple-limit="3"
                @clear="getUserLineData"
                @remove-tag="getUserLineData"
                @visible-change="handleUserMultiSelect">
                <el-option
                  v-for="dict in channelList"
                  :key="dict.channelCode"
                  :label="dict.channelName"
                  :value="dict.channelCode"
                />
              </el-select>
              <el-radio-group v-model="lineUserInfo.chartType" class="ml-10px" @change="getUserLineData">
                <el-radio-button value="user_contract">日签约用户数</el-radio-button>
                <el-radio-button value="user_uncontract">日解约用户数</el-radio-button>
              </el-radio-group>
            </div>
            <div class="flex items-center">
              <!-- <el-radio-group v-model="lineUserInfo.lidu" class="mr-10px" @change="getUserLineData">
                <el-radio-button value="day">日</el-radio-button>
                <el-radio-button value="week">周</el-radio-button>
                <el-radio-button value="month">月</el-radio-button>
              </el-radio-group> -->
              <el-date-picker 
                v-model="lineUserInfo.searchDate"
                :clearable="false"
                type="daterange"
                value-format="YYYYMMDD"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 240px"
                :disabled-date="handleDisabledDate"
                @change="getUserLineData">
              </el-date-picker>
            </div>
          </div>
          <div class="chart" id="userChart"></div>
        </div>
      </div>

      <div class="base-container mt-10px">
        <div class="title-box">
          <p class="title">渠道电子卡列表</p>
          <div class="flex items-center">
            <el-date-picker 
              v-model="cardInfo.searchDate"
              :clearable="false"
              type="month"
              value-format="YYYY-MM"
              style="width: 120px"
              :disabled-date="handleDisabledDate"
              @change="getCardList">
            </el-date-picker>
            <p class="more" @click="jumpUserList">更多</p>
          </div>
        </div>
        <el-table class="mt-10px" border v-loading="cardInfo.loading" :data="cardInfo.list">
          <el-table-column label="来源渠道" align="center" prop="channelName" min-width="150" show-overflow-tooltip />
          <el-table-column label="用户名" align="center" prop="userName" min-width="150" show-overflow-tooltip />
          <el-table-column label="手机号码" align="center" prop="mobile" min-width="120" />
          <el-table-column label="用户状态" align="center" prop="status" min-width="100">
            <template #default="scope">
              <dict-tag :options="plat_user_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="支付模式" align="center" prop="payModel" min-width="110">
            <template #default="scope">
              <dict-tag :options="plat_order_pay_mode" :value="scope.row.payModel"/>
            </template>
          </el-table-column>
          <el-table-column label="电子卡号" align="center" prop="cardNo" min-width="150" show-overflow-tooltip />
          <el-table-column label="余额（元）" align="center" prop="amount" min-width="100">
            <template #default="scope">
              <span>{{ formatAmount(scope.row.amount) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="cardInfo.total>0"
        class="page"
        :total="cardInfo.total"
        v-model:page="cardInfo.pageNum"
        v-model:limit="cardInfo.pageSize"
        @pagination="getCardList"
      />
    </template>
  </div>
</template>

<script setup>
import { nextTick, reactive } from 'vue'
import { useTransition, TransitionPresets } from '@vueuse/core'
import { 
  getTotalOrderDataApi,
  getTodayOrderDataApi,
  getOrderTrendApi
} from "../api/statistic/home"
import { listChannel } from "../api/channel/platchannelinfo"
import { listPlatuserinfo } from "@/api/user/list"

// import gsap from 'gsap'
import * as echarts from 'echarts'
import { chart_line } from '../utils/echarts'
import { deepClone } from '../utils/index'
import useUserStore from '@/store/modules/user'

const router = useRouter()
const { proxy } = getCurrentInstance()
const { plat_user_status, plat_order_pay_mode } = proxy.useDict('plat_user_status', 'plat_order_pay_mode')

const channelList = ref([])
const hasPermissions = ref(true)

const duration = 1500
const total = ref({
  total_fee: 0,
  total_order: 0,
  total_user: 0
})
const totalRes = ref({})
const today = ref({
  total_fee: 0,
  total_order: 0,
  total_user: 0
})
const todayRes = ref({
  total_fee_data: {},
  total_num_data: {},
  car_register_data: {}
})
const lineOrderInfo = ref({
  searchDate: [],
  channelCode: [],
  chartType: 'trade_pay_fee',    // trade_pay_fee 交易金额 trade_count 交易笔数 trade_user 交易用户数
  lidu: 'day',  // day week month
})
const lineUserInfo = ref({
  searchDate: [],
  channelCode: [],
  chartType: 'user_contract',    // user_contract 日签约用户数  user_uncontract 日解约用户数
  lidu: 'day',  // day week month
})
const cardInfo = ref({
  searchDate: null,
  total: 1,
  pageNum: 1,
  pageSize: 10,
  loading: false,
  list: []
})

onMounted(() => {
  const permissions = useUserStore().permissions
  const all_permission = "*:*:*"
  hasPermissions.value = permissions.includes('home') || permissions.includes(all_permission)
  if (hasPermissions.value) {
    cardInfo.value.searchDate = proxy.parseTime(new Date(), '{y}-{m}')
    const currentDate = proxy.parseTime(new Date(), '{y}{m}{d}')
    let date = new Date()
    date.setDate(date.getDate() - 31)
    let yesterday = new Date()
    yesterday.setDate(yesterday.getDate() - 1)
    lineOrderInfo.value.searchDate = [proxy.parseTime(date, '{y}{m}{d}'), proxy.parseTime(yesterday, '{y}{m}{d}')]
    lineUserInfo.value.searchDate = lineOrderInfo.value.searchDate
    getChannelList()
    getTotalData()
    getCardList()
  }
})

const handleOrderMultiSelect = (val) => {
  if (!val) {
    getOrderLineData()
  }
}

const handleUserMultiSelect = (val) => {
  if (!val) {
    getUserLineData()
  }
}

const handleDisabledDate = (date) => {
  date = proxy.parseTime(date, '{y}-{m}-{d}')
  const currentDate = proxy.parseTime(new Date(), '{y}-{m}-{d}')
  return date >= currentDate
}

// 获取月份的第一天与最后一天
const getMonthDay = (yearMonth) => {
  const [year, month] = yearMonth.split('-').map(Number) 
  const firstDay = new Date(year, month - 1, 1)  
  const lastDayOfMonth = new Date(year, month, 0)  
    
  const formatDate = (date) => {  
    const year = date.getFullYear()  
    const month = (date.getMonth() + 1).toString().padStart(2, '0') 
    const day = date.getDate().toString().padStart(2, '0')  
    return `${year}-${month}-${day}`
  }
  return [formatDate(firstDay), formatDate(lastDayOfMonth)]
}

// 渠道电子卡列表
const getCardList = () => {
  cardInfo.value.loading = true
  const monthDay = getMonthDay(cardInfo.value.searchDate)
  const params = {
    pageNum: cardInfo.value.pageNum,
    pageSize: cardInfo.value.pageSize,
    registerBeginTime: monthDay[0],
    registerEndTime: monthDay[1],
    orderType: 1
  }
  listPlatuserinfo(params).then(response => {
    cardInfo.value.list = response.rows
    cardInfo.value.total = response.total
    cardInfo.value.loading = false
  })
}

// 渠道列表
const getChannelList = () => {
  const params = {
    pageNum: 1,
    pageSize: 1000,
  }
  listChannel(params).then(response => {
    channelList.value = response.rows
    getOrderLineData()
    getUserLineData()
  })
}

// 获取累计数据
const getTotalData = () => {
  getTotalOrderDataApi({}).then(res => {
    // total.value = res.data || {}
    totalRes.value = res.data || {}
    setTotalAnimation()
  })
  getTodayOrderDataApi({}).then(res => {
    todayRes.value = res.data
    setTodayAnimation()
  })
}

// 跳转用户列表
const jumpUserList = () => {
  router.push('platuser/list')
}

// 订单折线图
const getOrderLineData = () => {
  const params = {
    beginDate: lineOrderInfo.value.searchDate[0],
    endDate: lineOrderInfo.value.searchDate[1],
    lidu: lineOrderInfo.value.lidu,
    chartType: lineOrderInfo.value.chartType,
    channelCodes: lineOrderInfo.value.channelCode.join(',')
  }
  getOrderTrendApi(params).then(response => {
    setLineChart(response.data, 'orderChart')
  })
}

// 用户折线图
const getUserLineData = () => {
  const params = {
    beginDate: lineUserInfo.value.searchDate[0],
    endDate: lineUserInfo.value.searchDate[1],
    lidu: lineUserInfo.value.lidu,
    chartType: lineUserInfo.value.chartType,
    channelCodes: lineUserInfo.value.channelCode.join(',')
  }
  getOrderTrendApi(params).then(response => {
    setLineChart(response.data, 'userChart')
  })
}

// 设置折线图
const setLineChart = (res, domId) => {
  const keys = Object.keys(res)
  let legend = []
  let xData = []
  let series = []
  for (let i = 0; i < keys.length; i++) {
    const code = keys[i]
    const channel = channelList.value.find(obj => {
      return obj.channelCode == code
    })
    if (channel) {
      legend.push(channel.channelName)
    }
    const dataArr = res[code].trend_map.list
    let yArr = []
    dataArr.forEach(item => {
      if (i === 0) {
        xData.push(item.ref_date_format)
      }
      yArr.push(item.val)
    })
    let info = {
      name: channel ? channel.channelName : '',
      type: 'line',
      smooth: true,
      data: yArr
    }
    series.push(info)
  }

  const dom = document.getElementById(domId)
  if (echarts.getInstanceByDom(dom)) {
    echarts.dispose(dom)
  }
  const chart = echarts.init(dom)
  let options = deepClone(chart_line)
  options.xAxis.data = xData
  options.series = series
  options.legend.data = legend
  if (domId == 'orderChart') {
    options.toolbox.feature.saveAsImage.name = '渠道订单趋势'
  } else {
    options.toolbox.feature.saveAsImage.name = '渠道用户趋势'
  }
  chart.setOption(options, true)
}

// 统计数字滚动动画
const setTotalAnimation = () => {
  const totalFee = ref(total.value.total_fee)
  total.value.total_fee = useTransition(totalFee, {
    duration: duration,
    // transition: TransitionPresets.easeInOutCubic
  })
  totalFee.value = Number(totalRes.value.total_fee)

  const totalOrder = ref(total.value.total_order)
  total.value.total_order = useTransition(totalOrder, {
    duration: duration
  })
  totalOrder.value = Number(totalRes.value.total_order)

  const totalUser = ref(total.value.total_user)
  total.value.total_user = useTransition(totalUser, {
    duration: duration
  })
  totalUser.value = Number(totalRes.value.total_user)
}

const setTodayAnimation = () => {
  const todayFee = ref(today.value.total_fee)
  today.value.total_fee = useTransition(todayFee, {
    duration: duration,
    // transition: TransitionPresets.easeInOutCubic
  })
  todayFee.value = Number(todayRes.value.total_fee_data.today_total_fee)

  const todayOrder = ref(today.value.total_order)
  today.value.total_order = useTransition(todayOrder, {
    duration: duration
  })
  todayOrder.value = Number(todayRes.value.total_num_data.today_total_num)

  const todayUser = ref(today.value.total_user)
  today.value.total_user = useTransition(todayUser, {
    duration: duration
  })
  todayUser.value = Number(todayRes.value.car_register_data.card_register_today_num)
}

</script>

<style scoped lang="scss">
@import '../assets/styles/statistic.scss';

.top-card-box {
  width: 33.33% !important;
}

.chart {
  width: 100%;
  height: 360px !important;
  margin-top: 15px;
}

.page {
  left: 0 !important;
  margin-top: 20px;
  position: relative !important;
}

</style>

